<?php


namespace app\api\console;


use app\api\service\OrderService;
use app\api\service\PharmacyOrderService;
use app\api\service\PharmacyWalletService;
use dada\api\AddShopApi;
use dada\client\DadaRequestClient;
use dada\config\Config;
use dada\config\UrlConfig;
use dada\model\QueryOrderDetail;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use dada\api\BaseApi;
use think\Log;

class ToDaDaGetOrderStatus extends Command
{
    protected function configure()
    {
        $this
            // 命令的名字（"think" 后面的部分）
            ->setName('app:update:status:fromdada')

            // 运行 "php think list" 时的简短描述
            ->setDescription('去达达获取订单的派送状态.')

            // 运行命令时使用 "--help" 选项时的完整命令描述
            ->setHelp("去达达获取订单的派送状态...")
        ;
    }


    protected function execute(Input $input, Output $output)
    {

        $orderService = new OrderService();

        $data = $orderService->fetchSendingOrder();

        $pharmacyOrderService = new PharmacyOrderService();

        $pharmacyWalletService = new PharmacyWalletService();

        $config = Config::newConfig();

        foreach ($data as $datum) {

            try{

                $id = $datum['id'];

                $orderId = $datum['order_id'];

                $pharmacyId = $datum['pharmacy_id'];

                $queryOrder = new QueryOrderDetail();
                $queryOrder->setOrderId($orderId);

                $queryOrder = new BaseApi(UrlConfig::QUERY_ORDER_DETAIL, json_encode($queryOrder));

                $dada_client = new DadaRequestClient($config, $queryOrder);

                $resp = $dada_client->makeRequest();

                if ($resp->getCode() !== 0) {
                    throwBusinessException($resp->getMsg());
                };

                $result = $resp->getResult();

                $statusCode = $result['statusCode'];

                if($statusCode == 4){
                    $pharmacyOrderService->updatePharmacyOrderStatusById($pharmacyId, $id, ['status'=>888]);

                    $settleMentAmount = $datum['settlement_amount'];

                    $pharmacyWalletService->addOrUpdateWallet($pharmacyId, $settleMentAmount);

                }

            }catch (\Exception $e){
                Log::error($e->getMessage());
            }


        }

    }
}